<template>
  <div class="message-list-container" ref="messageListContainer">
    <div
      v-for="(message, index) in displayedMessages"
      :key="index"
      class="message-item"
      :style="{ opacity: 0.5 }"
    >
      {{ message.content }}
    </div>
  </div>
</template>

<script>
export default {
  name: "MessageList",
  props: {
    messages: {
      type: Array,
      default: () => [],
    },
    maxDisplayedMessages: {
      type: Number,
      default: 20, // 默认显示100条消息
    },
  },
  data() {
    return {
      currentDisplayedMessages: [],
    };
  },
  computed: {
    displayedMessages() {
      return this.currentDisplayedMessages.slice(
        this.messages.length - this.maxDisplayedMessages,
        this.messages.length
      );
    },
  },
  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        this.$refs.messageListContainer.scrollTop =
          this.$refs.messageListContainer.scrollHeight;
      });
    },
    updateDisplayedMessages() {
      this.currentDisplayedMessages = this.messages.slice(
        -this.maxDisplayedMessages
      );
    },
  },
  mounted() {
    this.updateDisplayedMessages();
  },
  watch: {
    messages: {
      deep: true,
      handler() {
        this.updateDisplayedMessages();
      },
    },
  },
};
</script>

<style scoped>
.message-list-container {
  position: sticky;
  top: 0;
  height: 100%;
  overflow-y: auto;
}

.message-item {
  margin-bottom: 10px;
  font-size: 16px;
}
</style>
